//
//  TSMainPageTableViewCell.swift
//  TSProfitProject
//
//  Created by TMS on 2019/11/4.
//  Copyright © 2019 TMS. All rights reserved.
//

import UIKit
import HandyJSON

protocol TSMainPageTableViewCellDelegate : NSObjectProtocol {
    func countdownEnd(model:TSMainPageModel)
}

struct TSMainPageModel : HandyJSON {
    var interval = 0          // 倒计时
    var current : Int64 = 0           // 本期期号
    var newest : TSMainPageCurrentModel? = nil
    var title : String!       // 彩票名称
    var identifier : String!  // 定时器标识
    var imageName : String!
    var currentTime : String!
    
    var countdownFinished = false
 }

struct TSMainPageCurrentModel : HandyJSON {
    var code : String? = nil   // 上期中奖号码
    var issue : Int64 = 0             // 上期期号
}

class TSMainPageTableViewCell: UITableViewCell {
    
    weak var delegate : TSMainPageTableViewCellDelegate? = nil
    private var icon : UIView!
    private var titleLabel : UILabel!
    private var periodLabel : UILabel!
    private var resultView : UIView!
    private var currentPeriodLabel : UILabel!
    private var remainLabel : UILabel!
    private var coinLabel : UILabel!
    private var waterBillLabel : UILabel!
    private var img : UIImageView!
    private var model : TSMainPageModel? = nil
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.selectionStyle = .none
        configViews()
        
        NotificationCenter.default.addObserver(self, selector: #selector(self.countDownNotification), name: .OYCountDownNotification, object: nil)
    }
    
    required init?(coder: NSCoder) {
        
        super.init(coder: coder)
        NotificationCenter.default.addObserver(self, selector: #selector(self.countDownNotification), name: .OYCountDownNotification, object: nil)
        
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupCell(model:TSMainPageModel) {
            
        self.model = model
        
        img.image = UIImage(named: model.imageName)
        icon.backgroundColor = model.title == "北京赛车" ? BASE_BLUE_COLOR : BASE_RED_COLOR
        titleLabel.text = model.title!
        periodLabel.text = "\(model.newest?.issue ?? 0)期开奖号码"
        currentPeriodLabel.text = "当前期数：\(model.current)"
        if self.model!.countdownFinished {
            remainLabel.attributedText = createAttributedString(str: "开奖中", attributedStr: "开奖中")
        }
        
        let subviews = resultView.subviews
        for view in subviews {
            view.removeFromSuperview()
        }
        
        let numArray = model.newest?.code?.components(separatedBy: ",")
        if numArray?.count ?? 0 > 0 {
            var tempArray = Array<UILabel>()
            for index in 0..<(numArray!.count) {
                let char = numArray![index]
                let item = createNumeralView(number: char)
                resultView.addSubview(item)
                tempArray.append(item)
            }
            tempArray.snp.makeConstraints { (make) in
                make.top.equalToSuperview()
                if SCREEN_WIDTH <= 320 {
                    make.width.height.equalTo(CGSize(width: 12, height: 12))
                } else {
                    make.width.height.equalTo(CGSize(width: 15, height: 15))
                }
            }
            for index in 0..<(numArray!.count) {
                let label = tempArray[index]
                label.snp.makeConstraints { (make) in
                    if SCREEN_WIDTH <= 320 {
                        make.leading.equalTo(index*14)
                    } else {
                        make.left.equalTo(index*20)
                    }
                }
                
            }
        }
    }

    @objc private func countDownNotification() {
        
        let intervalModel = OYCountDownManager.sharedManager.timeIntervalDict[self.model!.identifier]
        
        if intervalModel == nil {
            return
        }
        
        let timeInterval = OYCountDownManager.sharedManager.timeIntervalWithIdentifier(identifier: self.model!.identifier)
        let countDown = self.model!.interval - timeInterval
        if countDown <= 0 { // 倒计时结束时回调
            
            self.model!.countdownFinished = true
            if self.delegate != nil {
                self.delegate?.countdownEnd(model: self.model!)
            }
            OYCountDownManager.sharedManager.removeSourceWithIdentifier(identyfier: self.model!.identifier)
            remainLabel.attributedText = createAttributedString(str: "开奖中", attributedStr: "开奖中")
            return;
        }
        if !self.model!.countdownFinished {
            let remainStr = String(format: "%02d:%02d:%02d", countDown/3600, (countDown/60)%60, countDown%60)
            remainLabel.attributedText = createAttributedString(str: "剩余时间："+remainStr, attributedStr: remainStr)
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

extension TSMainPageTableViewCell {
    
    func configViews() {
        
        let bgView = UIImageView.init(image: UIImage(named: "main_cell_bg"))
        self.contentView.addSubview(bgView)
        bgView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview().inset(12)
            make.top.bottom.equalToSuperview()
        }
        
        icon = UIView.init()
        icon.backgroundColor = BASE_BLUE_COLOR
        bgView.addSubview(icon)
        icon.snp.makeConstraints { (make) in
            make.left.equalTo(15)
            make.top.equalTo(8)
            make.size.equalTo(CGSize(width: 3, height: 14))
        }
        
        let detailBtn = UIButton.init()
        detailBtn.setTitle("详情", for: .normal)
        detailBtn.isEnabled = false
        detailBtn.setTitleColor(UIColor.hexadecimalColor(hexadecimal: "#989898"), for: .normal)
        detailBtn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        detailBtn.setEnlargeEdgeNumber(enlarge: 10)
        bgView.addSubview(detailBtn)
        detailBtn.snp.makeConstraints { (make) in
            make.right.equalToSuperview().inset(15)
            make.centerY.equalTo(icon)
            make.width.equalTo(25)
        }
        
        titleLabel = createLabel(title: "幸运飞艇", fontSize: 13, textColor: "#282828")
        bgView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.centerY.equalTo(icon)
            make.left.equalTo(icon.snp.right).offset(5)
            make.right.equalTo(detailBtn.snp.left).offset(-5)
        }
        
        img = UIImageView.init()
        bgView.addSubview(img)
        img.snp.makeConstraints { (make) in
            make.left.equalTo(titleLabel)
            make.top.equalTo(titleLabel.snp.bottom).offset(17)
            make.size.equalTo(CGSize(width: 92, height: 89))
        }
        
        periodLabel = createLabel(title: "740286期开奖号码", fontSize: 13, textColor: "#000000")
        bgView.addSubview(periodLabel)
        periodLabel.snp.makeConstraints { (make) in
            make.top.equalTo(icon.snp.bottom).offset(10)
            make.left.equalTo(img.snp.right).offset(25)
            make.right.equalTo(-10)
        }
        
        resultView = UIView.init()
        resultView.backgroundColor = WHITE_COLOR
        bgView.addSubview(resultView)
        resultView.snp.makeConstraints { (make) in
            make.left.right.equalTo(periodLabel)
            make.top.equalTo(periodLabel.snp.bottom).offset(10)
            make.height.equalTo(15)
        }
        
        currentPeriodLabel = createLabel(title: "当前期数：740286", fontSize: 13, textColor: "#000000")
        bgView.addSubview(currentPeriodLabel)
        currentPeriodLabel.snp.makeConstraints { (make) in
            make.left.right.equalTo(periodLabel)
            make.top.equalTo(resultView.snp.bottom).offset(12)
//            make.centerY.equalTo(img)
        }
        
        remainLabel = createLabel(title: "", fontSize: 11, textColor: "#FC4F53")
        remainLabel.attributedText = createAttributedString(str: "剩余时间：00:00:00", attributedStr: "00:00:00")
        bgView.addSubview(remainLabel)
        remainLabel.snp.makeConstraints { (make) in
            make.left.right.equalTo(periodLabel)
            make.bottom.equalTo(img)
        }
        
    }
    
    func createLabel(title : String, fontSize : CGFloat, textColor : String) -> UILabel {
        
        let label = UILabel.init()
        label.text = title
        label.font = UIFont.systemFont(ofSize: fontSize)
        label.textColor = UIColor.hexadecimalColor(hexadecimal: textColor)
        return label
    }
    
    func createAttributedString(str : String, attributedStr : String) -> NSAttributedString {
        
        let nsStr = NSString(string: str)
        let attribute = NSMutableAttributedString.init(string: str)
    attribute.addAttributes([NSAttributedString.Key.font:UIFont.systemFont(ofSize: 11), NSAttributedString.Key.foregroundColor:UIColor.black], range: NSMakeRange(0, str.count))
        
        attribute.addAttributes([NSAttributedString.Key.foregroundColor:BASE_RED_COLOR], range: nsStr.range(of: attributedStr))
        
        return attribute.copy() as! NSAttributedString
    }
    
    func createNumeralView(number:String) -> UILabel {
        let label = UILabel.init()
        label.text = number
        label.font = UIFont.systemFont(ofSize: 12*T_ScreenScale())
        label.textAlignment = .center
        label.textColor = WHITE_COLOR
        label.backgroundColor = BASE_BLUE_COLOR
        if SCREEN_WIDTH <= 320 {
            label.layer.cornerRadius = 6
        } else {
            label.layer.cornerRadius = 7.5
        }
        label.layer.masksToBounds = true
        label.adjustsFontSizeToFitWidth = true
        label.minimumScaleFactor = 0.6
        return label
    }
}
